<!-- 执行巡检 -->
<template>
	<view class="no-warpper">
		<view class="nl-shadow-box">
			<view class="nl-flex-list" @click="openPicker()">
				<text>巡检情况</text>
				<view :class="patrolTypeName ? 'right':'right-grey'">
					{{patrolTypeName ? patrolTypeName : '选择巡检情况'}}
				</view>
				<u-icon class="margin-left" name="arrow-right" color="#414141" size="24"></u-icon>
			</view>

			<view class="nl-flex-title">巡检说明</view>
			<view class="textarea-padding">
				<u-input v-model="params.description" placeholder-style="color: #AFAFAF;font-size: 28rpx;"
					type="textarea" border placeholder="请输入巡检说明" />
			</view>

			<!-- 图片上传 -->
			<uploadImg @photosData="photosData()" :prompt="true" :maxCount="4" :sourceType="['camera']"></uploadImg>
			<view class="button-lg" @click="submit()">
				<button>提交</button>
			</view>

			<!-- 图像 -->
			<canvas class="watermark-canvas" :style="{'width':watermarkW,'height': watermarkH}"
				canvas-id="watermarkCanvas" />
		</view>
		<u-picker mode="selector" confirm-color="#1585FC" v-model="pickerShow" :default-selector="[0]"
			:range="selectorObj" range-key="name" @confirm="cycleChange"></u-picker>
	</view>
</template>

<script>
	import {
		updateInspectionTaskDetail
	} from 'api/patrol';
	import {
		mapState
	} from 'vuex';
	import {
		dateFormat,
	} from '@/utils/dateUtil.js'

	export default {
		data() {
			return {
				// 选择器
				pickerShow: false,
				selectorObj: [{
					name: '正常',
					state: '10001'
				}, {
					name: '异常',
					state: '20002'
				}],
				patrolTypeName: '',
				// 需要提交的内容
				params: {
					taskId: '',
					taskDetailId: '',
					inspectionId: '',
					inspectionName: '',
					communityId: '',
					patrolType: '',
					description: '',
					photos: [],
					userId: '',
					userName: '',
				},

				// 水印
				phoneWidth: '',
				watermarkW: '',
				watermarkH: '',
			};
		},
		computed: {
			...mapState('user', ['userInfo', 'userCommunity'])
		},
		onLoad(options) {
			this.getPhoneInfo()
			let data = JSON.parse(options.item)
			console.log('options', data)

			this.params.taskId = data.taskId
			this.params.taskDetailId = data.taskDetailId
			this.params.inspectionId = data.inspectionId
			this.params.inspectionName = data.inspectionName
			this.params.communityId = data.communityId
			this.params.userId = this.userInfo.userId
			this.params.userName = this.userInfo.userName
		},
		methods: {
			/**
			 * 打开巡检情况选择器
			 */
			openPicker() {
				this.pickerShow = true
			},
			/**
			 * 选择巡检情况
			 */
			cycleChange(e) {
				let index = e[0]
				this.patrolTypeName = this.selectorObj[index].name;
				this.params.patrolType = this.selectorObj[index].state;
			},
			/**
			 * 图片上传列表
			 */
			photosData(data) {
				uni.showLoading({
					title: '添加水印',
					mask: true,
				})
				setTimeout(() => {
					console.log('photosData', data)
					this.watermark(data[data.length - 1])
				}, 1000)
			},
			/**
			 * 获取手机信息
			 */
			getPhoneInfo() {
				let that = this
				uni.getSystemInfo({
					success: function(res) {
						that.phoneWidth = res.windowWidth
					}
				});
			},
			/**
			 * 添加水印
			 */
			watermark(data) {
				let that = this
				let watermarkText = [`时间：${dateFormat("YYYY-mm-dd HH:MM:SS", new Date())}`,
					`地点：${this.params.inspectionName}`, `巡检人：${this.userInfo.userName}`
				]
				let ctx = uni.createCanvasContext('watermarkCanvas')
				that.watermarkW = `${data.width*2}rpx`
				that.watermarkH = `${data.height*2}rpx`
				//将图片src放到cancas内，宽高为图片大小
				ctx.drawImage(data.path, 0, 0, data.width, data.height)

				console.log(123, data.width, data.height)
				let size
				if (data.width < data.height) {
					size = (data.width * 14) / that.phoneWidth
				} else {
					size = (data.height * 14) / that.phoneWidth
				}
				ctx.setFontSize(size)
				ctx.setFillStyle('#f9f9f9')

				for (let i = 0; i < watermarkText.length; i++) {
					let w
					let h
					if (i === 0) {
						w = size
						h = data.height - size * (i + 1) - 24 * (i + 3)
					} else {
						w = size
						h = data.height - size * (i + 1) - 24 * (i + 3)
					}
					ctx.fillText(watermarkText[i], Math.round(w), h)
				}
				ctx.fillText(`小区：${that.userCommunity.name}`, size, size + 24)

				ctx.draw(false, () => {
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: 'watermarkCanvas',
							destWidth: data.width/2,
							destHeight: data.height/2,
							success: (res) => {
								// 将图片转为base64
								uni.getFileSystemManager().readFile({
									filePath: res.tempFilePath,
									encoding: 'base64',
									success: res => {
										let imgObj = {
											photo: ''
										}
										imgObj.photo = 'data:image/jpeg;base64,' + res
											.data
										that.params.photos.push(imgObj)
										uni.hideLoading()
									}
								})
							}
						});
					}, 1000);
				});
			},
			/**
			 * 提交
			 */
			submit() {
				var that = this
				console.log(this.params)
				let text = '';
				let state = '0';

				if (!that.params.patrolType && state == '0') {
					text = '请选择巡检情况';
					state = '1'
				}

				if (!that.params.description && state == '0') {
					text = '请输入巡检说明';
					state = '1'
				}

				if (state == '1') {
					uni.showToast({
						title: text,
						icon: 'none',
						duration: 1500
					})
					return false
				}

				updateInspectionTaskDetail(that.params).then((res) => {
					console.log('updateInspectionTaskDetail', res)
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 1500
					})

					if (res.msg == '成功') {
						setTimeout(() => {
							uni.$emit('refresh');
							uni.navigateBack({
								delta: 1
							});
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.nl-flex-title {
		border-bottom: none
	}

	.textarea-padding {
		padding: 0 24rpx 24rpx;
		border-bottom: 2rpx solid $uni-bg-color-grey;
	}

	.watermark-canvas {
		position: absolute;
		top: -99999rpx;
		left: 0;
		z-index: -1;
		opacity: 0;
	}
</style>
